package com.ruoyi.web.controller.product.service.Impl;

import com.ruoyi.common.constant.*;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.entity.DO.member.MemberBalanceRecordDO;
import com.ruoyi.common.entity.DO.member.MemberCreditRecordDO;
import com.ruoyi.common.entity.DO.member.MemberDO;
import com.ruoyi.common.entity.DO.order.MemberRechargeOrderDO;
import com.ruoyi.common.entity.DO.product.ProductCategoryLinkDO;
import com.ruoyi.common.entity.DO.product.ProductDO;
import com.ruoyi.common.entity.VO.product.ProductCategorySearchVO;
import com.ruoyi.common.entity.VO.product.ProductSearchVO;
import com.ruoyi.common.entity.VO.product.ProductVO;
import com.ruoyi.common.entity.VO.product.RechargeProductVO;
import com.ruoyi.common.entity.VO.shop.ShopProductSearchVO;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.mapper.IBackProductMapper;
import com.ruoyi.system.mapper.IBackShopProductMapper;
import com.ruoyi.web.controller.common.mapper.IBackCommonImageMapper;
import com.ruoyi.web.controller.product.mapper.IBackProductCategoryLinkMapper;
import com.ruoyi.web.controller.product.mapper.IBackProductCategoryMapper;
import com.ruoyi.web.controller.product.service.IBackProductCategoryService;
import com.ruoyi.web.controller.product.service.IBackProductService;
import com.ruoyi.web.controller.tool.IdWorker;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

import static org.springframework.transaction.annotation.Propagation.REQUIRES_NEW;

@Service()
public class BackProductServiceImpl implements IBackProductService {

    @Resource
    private IBackProductCategoryService categoryService;

    @Resource
    private IBackShopProductMapper shopProductMapper;

    @Resource
    private IBackProductMapper productMapper;

    @Resource
    private IBackProductCategoryMapper productCategoryMapper;

    @Resource
    private IBackProductCategoryLinkMapper categoryLinkMapper;

    @Resource
    private IBackCommonImageMapper commonImageMapper;

    @Override
    public List<ProductVO> searchProductList(ProductSearchVO productSearchVO) {
        List<ProductVO> list = new ArrayList<>();
        try {
            productSearchVO.setIsDelete(0);
            list = productMapper.searchList(productSearchVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<Ztree> selectProductTree() {
        List<Ztree> ztrees = categoryService.searchCategoryTree(new ProductCategorySearchVO());
        if (ztrees.size() > 0) {
            ProductSearchVO searchVO = new ProductSearchVO();
            searchVO.setIsDelete(0);
            searchVO.setIsEnable(1);
            List<ProductVO> productList = productMapper.searchList(searchVO);
            for (ProductVO productVO : productList) {
                Ztree ztree = new Ztree();
                ztree.setId(productVO.getId() * 10000);
                ztree.setpId(productVO.getCategoryId());
                ztree.setName(productVO.getProductName());
                ztree.setTitle(productVO.getProductName());
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    @Override
    public ProductVO getProductInfoById(Long productId) {
        return productMapper.getProductInfoById(productId);
    }

    @Override
    @Transactional
    public int insertProduct(ProductVO productVO) {
        ProductDO productDO = new ProductDO();
        //TODO：2021/10/18新增 用于计算
        Integer totalStock = 0;
        BigDecimal buyPrice = BigDecimal.ZERO;
        BigDecimal price = BigDecimal.ZERO;
        if (StringUtils.isEmpty(productVO.getCategoryIds())) {
            throw new BusinessException("请至少选择一个商品分类!");
        }
        productDO.setProductSn(NumberUtils.generateCode(8));
        productDO.setProductName(productVO.getProductName());
        productDO.setBuyUnit(productVO.getBuyUnit());
        //TODO：2021/10/18注释 利用SKU算出来
//        productDO.setBuyPrice(productVO.getBuyPrice());
//        productDO.setPrice(productVO.getPrice());
//        productDO.setStock(productVO.getStock());
//        productDO.setWeight(productVO.getWeight());
        productDO.setAppendRemark(productVO.getAppendRemark());
        productDO.setCoverUrl(productVO.getCoverUrl());
        productDO.setOrderNum(productVO.getOrderNum());
        productDO.setMemo(productVO.getMemo());
        productDO.setIsEnable(productVO.getIsEnable());
        productDO.setCreateTime(new Date());
        productDO.setCreateBy(productVO.getCreateBy());
        productDO.setIsDelete(0);
        productDO.setIsPromotion(0);
        productDO.setHasAttribute(0);
        List<String> productCategoryNameList = productCategoryMapper.getCategoryNameList(productVO.getCategoryIds());
        String productCategory = StringUtils.join(productCategoryNameList.toArray(), ',');
        productDO.setProductCategory(productCategory);
        productMapper.insertSelective(productDO);
        Long[] categoryIdArr = Convert.toLongArray(productVO.getCategoryIds());
        for (Long categoryId : categoryIdArr
        ) {
            ProductCategoryLinkDO categoryLinkDO = new ProductCategoryLinkDO();
            categoryLinkDO.setCategoryId(categoryId);
            categoryLinkDO.setProductId(productDO.getId());
            categoryLinkDO.setCreateTime(productDO.getCreateTime());
            categoryLinkDO.setCreateBy(productDO.getCreateBy());
            categoryLinkMapper.insertSelective(categoryLinkDO);
        }
        if (productVO.getTempId() != null) {
            commonImageMapper.linkProduct(productDO.getId(), productVO.getTempId());
        }
        productDO.setStock(totalStock);
        productDO.setPrice(price);
        productDO.setBuyPrice(buyPrice);
        productMapper.updateByPrimaryKeySelective(productDO);
        if (productDO.getIsEnable() == 1) {
            //TODO:平台商品上架，同步到所有店铺
            Long[] productIdArr = new Long[1];
            productIdArr[0] = productDO.getId();
            AsyncManager.me().execute(AsyncFactory.productEnableAsyncToShop(productIdArr));
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateProduct(ProductVO productVO) {
        boolean isAsync = false;
        if (StringUtils.isNotEmpty(productVO.getIds())) {
            productVO.setIdArr(Convert.toLongArray(productVO.getIds()));
            if (productVO.getIdArr().length > 1) {
                productMapper.multiUpdate(productVO);
                if (productVO.getIsEnable() == 1) {
                    //TODO:批量上架，同步上架到每一个门店
                    AsyncManager.me().execute(AsyncFactory.productEnableAsyncToShop(productVO.getIdArr()));
                }
                return 1;
            } else {
                productVO.setId(productVO.getIdArr()[0]);
            }
        }
        ProductDO productDO = productMapper.selectByPrimaryKey(productVO.getId());
        if (productDO == null || productDO.getIsDelete() == 1) {
            throw new BusinessException("商品已被删除，请刷新后重试！");
        }
        if (productVO.getIsEnable() != null && productVO.getIsEnable() == 1 && !productVO.getIsEnable().equals(productDO.getIsEnable())) {
            isAsync = true;
        }
        productDO.setProductName(productVO.getProductName());
        productDO.setAppendRemark(productVO.getAppendRemark());
        productDO.setCoverUrl(productVO.getCoverUrl());
        productDO.setBuyUnit(productVO.getBuyUnit());
        productDO.setOrderNum(productVO.getOrderNum());
        productDO.setMemo(productVO.getMemo());
        productDO.setIsEnable(productVO.getIsEnable());
        productDO.setUpdateBy(productVO.getUpdateBy());
        productDO.setUpdateTime(new Date());
        if (StringUtils.isNotEmpty(productVO.getCategoryIds())) {
            categoryLinkMapper.deleteByProductId(productDO.getId());
            List<String> productCategoryNameList = productCategoryMapper.getCategoryNameList(productVO.getCategoryIds());
            Long[] categoryIdArr = Convert.toLongArray(productVO.getCategoryIds());
            String productCategory = StringUtils.join(productCategoryNameList.toArray(), ',');
            productDO.setProductCategory(productCategory);
            for (Long categoryId : categoryIdArr
            ) {
                ProductCategoryLinkDO categoryLinkDO = new ProductCategoryLinkDO();
                categoryLinkDO.setCategoryId(categoryId);
                categoryLinkDO.setProductId(productDO.getId());
                categoryLinkDO.setCreateTime(productDO.getCreateTime());
                categoryLinkDO.setCreateBy(productDO.getUpdateBy());
                categoryLinkMapper.insertSelective(categoryLinkDO);
            }
        }
        productMapper.updateByPrimaryKeySelective(productDO);
        if (isAsync) {
            //TODO:平台商品上架，同步到所有店铺
            Long[] productIdArr = new Long[1];
            productIdArr[0] = productVO.getId();
            AsyncManager.me().execute(AsyncFactory.productEnableAsyncToShop(productIdArr));
        }
        return 1;
    }

    @Override
    public String checkProductNameUnique(ProductSearchVO productSearchVO) {
        Long productId = StringUtils.isNull(productSearchVO.getProductId()) ? -1L : productSearchVO.getProductId();
        Long existId = productMapper.getIdByProductName(productSearchVO.getProductName());
        if (existId != null && !productId.equals(existId)) {
            return Constants.FAIL;
        }
        return Constants.SUCCESS;
    }

    @Override
    public int deleteProductById(Long id) {
        return productMapper.deleteProductById(id);

    }

}
